//
//  StartGroupChatVC.m
//  AAIM
//
//  Created by awh on 2019/12/1.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "StartGroupChatVC.h"
#import "CreateGroupChatVC.h"
#import "FriendChatSettingVC.h"

#import "FirendsTableViewCell.h"
#import "StartGroupCollectionViewCell.h"

#import "ContactModel.h"
#import "EMChineseToPinyin.h"

#import "ContactRequestLogic.h"
#import "ChatViewController.h"

#import "FriendsInfoViewController.h"
#import "ConversationsViewController.h"
@interface StartGroupChatVC ()<UICollectionViewDelegate,UICollectionViewDataSource,FirendsTableViewCellDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (nonatomic, strong) NSMutableArray<NSString *> *sectionTitles;
@property (nonatomic, strong) UICollectionView *  userlistView;
@property (nonatomic, strong) UITableView *  tableView;
@property (nonatomic, strong) NSMutableArray *collectionDataArray;
@property (nonatomic, strong) NSMutableArray *dataSources;
@property (nonatomic, strong) UIButton * groupChatBtn;

@property (nonatomic,strong) UIView *titleView;
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong)UILabel *searchTitle;
@property (nonatomic,strong) MJTableViewNullDataView * nullDataView;
@property (nonatomic,strong) NSMutableArray * searchArr;
@property (nonatomic,strong) NSMutableArray * membersArr;//群成员，不分群主和成员
@property (nonatomic,assign) BOOL isSearchRes;//是否为搜索结果
@end

@implementation StartGroupChatVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    _searchArr = [NSMutableArray array];
    _membersArr = [NSMutableArray array];
    [self crteateUI];
}
-(void)crteateUI
{
    [self createSelectedUserCollectionView];
    if (_type == 4) {
        self.gk_navTitle = @"群成员";
        self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, self.gk_navigationBar.bottom+47, SCREEN_WIDTH, SCREEN_HEIGHT-EMVIEWBOTTOMMARGIN-NavigationBarHeight-52) style:UITableViewStyleGrouped];
    }else if (_type == 5)
    {
        self.gk_navTitle = @"选择提醒的人";
        self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, self.gk_navigationBar.bottom+47, SCREEN_WIDTH, SCREEN_HEIGHT-EMVIEWBOTTOMMARGIN-NavigationBarHeight-52) style:UITableViewStyleGrouped];
        
    }
    else{
        
        self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, NavigationBarHeight+52, SCREEN_WIDTH, SCREEN_HEIGHT-EMVIEWBOTTOMMARGIN-NavigationBarHeight-52) style:UITableViewStyleGrouped];
    }
    
    self.tableView.rowHeight = 60.0f;
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    [self.tableView registerClass:[FirendsTableViewCell class] forCellReuseIdentifier:@"startGroupCell"];
    self.sectionTitles = [NSMutableArray array];
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.nullDataView];
    
    if (_type == 1 || _type == 2 ||_type == 3 ) {
        // 导航右按钮
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setImage:[UIImage imageNamed:@"icon_more"] forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(rightBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [rightBtn sizeToFit];
        [rightBtn setTitle:_type == 1?@"创建":_type==2?@"添加":@"移除" forState:UIControlStateNormal];
        [rightBtn setTitleColor:KHEXCOLOR(AllBackColor_titleColor) forState:UIControlStateNormal];
        rightBtn.frame = CGRectMake(0, 0, 44, 44);
        rightBtn.jk_touchAreaInsets = UIEdgeInsetsMake(20, 20, 20, 20);
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        self.gk_navigationItem.rightBarButtonItem = rightItem;
    }
    
    
    [self test];
}

- (void)test {
    [self showAlwaysTipHudWithText:@"加载中，请稍等"];
    if (_type == 2 ||_type ==1) {
        //先获取好友列表
        KWeakSelf;
        [ContactRequestLogic requestFriendListWithPage:@"1" Success:^(NSDictionary * _Nonnull Dict) {
            NSMutableArray *contactArray = [NSMutableArray array];
            NSLog(@"拉人进群：%@",Dict);
            for (NSDictionary * contactDic in Dict[@"data"]) {
                ContactModel *contactModel = [ContactModel mj_objectWithKeyValues:contactDic];
                if ([contactModel.fuuid isEqualToString:weakSelf.friendsFuuid]) {
                    contactModel.seleoctedState = YES;
                    [weakSelf.collectionDataArray addObject:contactModel];
                }
                [weakSelf.groupMemberAry enumerateObjectsUsingBlock:^(ContactModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj.fuuid isEqualToString:contactModel.fuuid]) {
                        contactModel.seleoctedState = YES;
                    }
                }];
                [contactArray addObject:contactModel];
                [self.membersArr addObject:contactModel];
            }
            [self sortAllContacts:contactArray];
        } failure:^(NSString * _Nonnull errMsg) {
            [self hideHud];
            [self showTipHudWithText:errMsg];
        }];
        
    }else{
        [ContactRequestLogic requestGroupqueryMembersWithgroupId:_groupID Query:@"" page:@"" Success:^(NSDictionary * _Nonnull Dict) {
            KWeakSelf;
            NSMutableArray *contactArray = [NSMutableArray array];
            if (weakSelf.type == 4) {
                [weakSelf.dataSources removeAllObjects];
                [self hideHud];
                NSMutableArray * groupMasterArr = [NSMutableArray array];
                NSMutableArray * groupMenberArr = [NSMutableArray array];
                [weakSelf.sectionTitles removeAllObjects];
                for (NSDictionary * contactDic in Dict[@"data"][@"list"]) {
                    ContactModel *contactModel = [ContactModel mj_objectWithKeyValues:contactDic];
                    if ([contactModel.fuuid isEqualToString:weakSelf.friendsFuuid]) {
                        contactModel.seleoctedState = YES;
                        [weakSelf.collectionDataArray addObject:contactModel];
                    }
                    [weakSelf.membersArr addObject:contactModel];
                    if ([contactModel.isMaster isEqualToString:@"1"]) {
                        [groupMasterArr addObject:contactModel];
                    }else{
                        [groupMenberArr addObject:contactModel];
                    }
                    
                }
                [weakSelf.dataSources addObject:groupMasterArr];
                [weakSelf.dataSources addObject:groupMenberArr];
                [weakSelf.tableView reloadData];
                [weakSelf.userlistView reloadData];
            }else{
             
                if (self.type==5) {
                    for (NSDictionary * contactDic in Dict[@"data"][@"list"]) {
                        ContactModel *contactModel = [ContactModel mj_objectWithKeyValues:contactDic];
                            [contactArray addObject:contactModel];
                    }
                    [self sortAllContacts:contactArray];
                    
                }else
                {
                    for (NSDictionary * contactDic in Dict[@"data"][@"list"]) {
                        ContactModel *contactModel = [ContactModel mj_objectWithKeyValues:contactDic];
                        if (![contactModel.isMaster isEqualToString:@"1"]) {
                            [contactArray addObject:contactModel];
                        }
                    }
                    [self sortAllContacts:contactArray];
                }
                
                //            [contactArray removeFirstObject];
            }
            NSLog(@"群成员… %@",Dict);
        } failure:^(NSString * _Nonnull errMsg) {
            [self hideHud];
            NSLog(@"出错%@",errMsg);
        }];
    }
    
    
    //    NSMutableArray *contactArray = [NSMutableArray array];
    //    NSArray *xings = @[@"安",@"霸",@"赵", @"钱", @"孙", @"李", @"周", @"吴", @"郑", @"王", @"冯", @"成"];
    //    NSArray *mings = @[@"w",@"bbbb",@"只", @"立", @"兰", @"胜", @"华", @"斌", @"闽", @"浩", @"公", @"贤"];
    //    for (int i = 0; i < 50; i ++) {
    //        ContactModel *contactor = [ContactModel new];
    //        contactor.username = [NSString stringWithFormat:@"%@%@", xings[arc4random() % 12], mings[arc4random() % 12]];
    //        [contactArray addObject:contactor];
    //
    //    }
    //    [self sortAllContacts:contactArray];
}

-(void)creatGroupChat{
    NSString * fuuid;
    NSString * fuuids;
    for (ContactModel * model in _collectionDataArray) {
        fuuid = [NSString stringWithFormat:@"%@",model.fuuid];
        if ([CommonTools isEmpty:fuuids]) {
            fuuids = [NSString stringWithFormat:@"%@",model.fuuid];
        }else{
            fuuids = [NSString stringWithFormat:@"%@,%@",fuuids,fuuid];
        }
    }
    [ContactRequestLogic requestInviteFriendsCreateGroupWithGroupName:@"" withInviteFuuids:fuuids isSelect:@"" Success:^(NSDictionary * _Nonnull Dict) {
        [self hideHud];
        NSLog(@"创建结果%@",Dict[@"message"]);
        NSLog(@"建群%@",Dict);
        [self showTipHudWithText:@"创建成功"];
        [[UserDataBaseTool shareUserDataBaseTool]reloadData:2 Success:^(BOOL isOK) {
            if (isOK) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemCreateGroup object:nil];
            }
        }];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 新建将要push的控制器
            ChatViewController *chatVC =[[ChatViewController alloc]init];
            chatVC.chatType = ChatTypeGroup;
            chatVC.hidesBottomBarWhenPushed = YES;
            chatVC.gk_navTitle = Dict[@"data"][@"groupName"];
            chatVC.receiverId = Dict[@"data"][@"id"];
            // 获取当前路由的控制器数组
            NSMutableArray *vcArray = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
            NSMutableArray * newVCAry = [NSMutableArray array];
            // 打印当前路由的控制器数组
            NSLog(@"1==the vcArray is %@", vcArray);
            // 获取档期控制器在路由的位置
            [vcArray enumerateObjectsUsingBlock:^(UIViewController * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx == 0) {
                    [newVCAry addObject:obj];
                    *stop = YES;
                }
                
            }];
            
            // 添加新控制器
            [newVCAry addObject: chatVC];
            
            // 打印新增后的控制器数组
            NSLog(@"3==the vcArray is %@", vcArray);
            // 重新设置当前导航控制器的路由数组
            [self.navigationController setViewControllers:newVCAry animated:YES];
            
        });
    } failure:^(NSString * _Nonnull errMsg) {
        [self hideHud];
        [self showTipHudWithText:errMsg];
    } ];
}

-(void)rightBtnDidClick:(UIButton*)sender
{
    //1发起群聊 2添加群成员 3删除群成员
    if (_type == 1) {
        //        CreateGroupChatVC * vc=[[CreateGroupChatVC alloc]init];
        //        vc.collectionDataArray = self.collectionDataArray;
        //        [self.navigationController pushViewController:vc animated:YES];
        if (_collectionDataArray.count == 0) {
            [self showTipHudWithText:@"请选择邀请的好友"];
            return;
        }
        [self showAlwaysTipHudWithText:@"请稍等"];
        [self creatGroupChat];
        
        
    }else if (_type == 2){
        [self inviteFriendJoinGroup];
    }else{
        [self deleteGroupMember];
    }
    
    
}

- (void)deleteGroupMember{
    NSString * joinGroupId;
    NSString * joinGroupIds;
    for (ContactModel * model in _collectionDataArray) {
        joinGroupId = [NSString stringWithFormat:@"%@",model.fuuid];
        if ([CommonTools isEmpty:joinGroupIds]) {
            joinGroupIds = [NSString stringWithFormat:@"%@",model.fuuid];
        }else{
            joinGroupIds = [NSString stringWithFormat:@"%@,%@",joinGroupIds,model.fuuid];
        }
    }
    [ContactRequestLogic requestDeleteGroupMembersWithGroupid:_groupID joinGroupIds:joinGroupIds Success:^(NSDictionary * _Nonnull Dict) {
        [self showTipHudWithText:Dict[@"message"]];
//        if (self.delegate) {
//            [self.delegate uploadGroupMember];
//        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //            FriendChatSettingVC * chatVC = [[FriendChatSettingVC alloc]init];
            //         [self.navigationController popToViewController:chatVC animated:YES];
            
            for (UIViewController *controller in self.navigationController.viewControllers) {
                if ([controller isKindOfClass:[ChatViewController class]]) {
                    ChatViewController *chatVC =(ChatViewController *)controller;
                    [self.navigationController popToViewController:chatVC animated:YES];
                }
            }
            
        });
    } failure:^(NSString * _Nonnull errMsg) {
        if (errMsg) {
            [self showTipHudWithText:errMsg];
        }else{
            [self showTipHudWithText:@"移除失败"];
        }
        
    }];
}

- (void)inviteFriendJoinGroup{
    NSString * fuuid;
    NSString * fuuids;
    for (ContactModel * model in _collectionDataArray) {
        fuuid = [NSString stringWithFormat:@"%@",model.fuuid];
        if ([CommonTools isEmpty:fuuids]) {
            fuuids = [NSString stringWithFormat:@"%@",model.fuuid];
        }else{
            fuuids = [NSString stringWithFormat:@"%@,%@",fuuids,fuuid];
        }
    }
    [ContactRequestLogic requestJoinGroupSetWithGroupId:_groupID GroupCode:@"" fuuids:fuuids reason:@"" type:@"1" Success:^(NSDictionary * _Nonnull Dict) {
        NSLog(@"邀请加入群聊%@",Dict);
        NSLog(@"邀请信息%@",Dict[@"message"]);
        [self showTipHudWithText:Dict[@"message"]];
        [[UserDataBaseTool shareUserDataBaseTool]reloadData:2 Success:^(BOOL isOK) {
            if (isOK) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemCreateGroup object:nil];
            }
        }];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            for (UIViewController *controller in self.navigationController.viewControllers) {
                if ([controller isKindOfClass:[ChatViewController class]]) {
                    ChatViewController *chatVC =(ChatViewController *)controller;
                    [self.navigationController popToViewController:chatVC animated:YES];
                }
            }
            
        });
        
    } failure:^(NSString * _Nonnull errMsg) {
        NSLog(@"邀请加入群聊:%@",errMsg);
        [self showTipHudWithText:errMsg];
    }];
    
}

- (UIView *)titleView {
    if (!_titleView) {
        _titleView = [[UIView alloc] init];
        _titleView.frame = CGRectMake(15, NavigationBarHeight+10, SCREEN_WIDTH - 30, 32);
        _titleView.backgroundColor = KHEXCOLOR(kGrayColor_f2);
        [_titleView configLayerWithBorderWidth:0 andWithCornerRadius:5 andWithBorderColor:[UIColor whiteColor]];
        
        UIImageView *imageView = [UIImageView new];
        imageView.image = [UIImage imageNamed:@"icon_sousuo"];
        imageView.frame = CGRectMake(10, 10, 13, 13);
        [_titleView addSubview:imageView];
        
        _textField = [[UITextField alloc] init];
        _textField.font = [UIFont systemFontOfSize:13];
        _textField.placeholder = @"搜索";
        _textField.frame = CGRectMake(30, 0, SCREEN_WIDTH - 70, 32);
        _textField.returnKeyType = UIReturnKeySearch;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.delegate = self;
        [_textField addTarget:self action:@selector(textFieldTextChange:) forControlEvents:UIControlEventEditingChanged];
        [_titleView addSubview:_textField];
    }
    return _titleView;
}
-(void)textFieldTextChange:(UITextField *)textField{
    self.nullDataView.hidden = YES;
    //    if (![NSObject ldy_isEmpty:textField.text]) {
    //        [self searchActionWithKeyWord:textField.text];
    //    }else
    //    {
    //        _searchTitle.hidden=YES;
    //    }
    //    if (![NSObject ldy_isEmpty:textField.text]) {
    //                [self.searchArr removeAllObjects];
    //
    //    }
    if (textField.text.length == 0) {
        _isSearchRes = NO;
        [self.searchArr removeAllObjects];//没有搜索内容，就清空旧的数组内容
        [self.tableView reloadData];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.searchArr removeAllObjects];
    if (![NSObject ldy_isEmpty:textField.text]) {
        [self.membersArr enumerateObjectsUsingBlock:^(ContactModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (_type == 4 ||_type == 3) {
                //                if ([obj.remark containsString:textField.text]) {
                //不区分大小写判断
                BOOL result =  [obj.remark caseInsensitiveCompare:textField.text] == NSOrderedSame;
                if (result || [obj.remark containsString:textField.text]) {
                    [self.searchArr addObject:obj];
                }
                
            }else if(_type == 2){
                //不区分大小写判断
                BOOL result =  [obj.nickname caseInsensitiveCompare:textField.text] == NSOrderedSame;
                if (result || [obj.nickname containsString:textField.text]) {
                    [self.searchArr addObject:obj];
                }
            }
        }];
        if (self.searchArr.count == 0) {
            self.nullDataView.hidden = NO;
        }
        _isSearchRes = YES;
        [self.tableView reloadData];
        
    }else
    {
        _textField.text = nil;
    }
    return YES;
}


-(void)createSelectedUserCollectionView
{
    self.collectionDataArray=[[NSMutableArray alloc]init];
    self.dataSources=[[NSMutableArray alloc]init];
    if (_type != 4){
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize=CGSizeMake(45, 45);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _userlistView=[[UICollectionView alloc]initWithFrame:CGRectMake(0  ,kTopHeight+45, SCREEN_WIDTH, 60) collectionViewLayout:layout];
        [_userlistView registerNib:[StartGroupCollectionViewCell registerNib] forCellWithReuseIdentifier:@"cell"];
        _userlistView.dataSource=self;
        _userlistView.delegate=self;
        _userlistView.backgroundColor=[UIColor whiteColor];
        [self.view addSubview:self.userlistView];
    }
    
    
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.collectionDataArray.count>0) {
        self.userlistView.hidden=NO;
        self.tableView.y=self.userlistView.bottom+10;
        self.tableView.height=SCREEN_HEIGHT-EMVIEWBOTTOMMARGIN-NavigationBarHeight-52-60;
    }else
    {
        self.userlistView.hidden=YES;
        self.tableView.y=self.titleView.bottom+10;
        self.tableView.height=SCREEN_HEIGHT-EMVIEWBOTTOMMARGIN-NavigationBarHeight-52;
    }
    return self.collectionDataArray.count;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0*SCALAE, 2*SCALAE, 0*SCALAE, 2*SCALAE);
}

// 两行cell之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    StartGroupCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    ContactModel * model =self.collectionDataArray[indexPath.row];
    cell.nameLabel.text=model.username;
    [cell.userAvatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,model.head]] placeholderImage:kHeadPlaceholderImage];
    return cell;
}
-(void)scrollBottom
{
    if (self.collectionDataArray.count > 0) {
        NSInteger toRow = self.collectionDataArray.count - 1;
        NSIndexPath *toIndexPath = [NSIndexPath indexPathForRow:toRow inSection:0];
        [self.userlistView scrollToItemAtIndexPath:toIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}

- (void)sortAllContacts:(NSArray *)aContactList
{
    [self.dataSources removeAllObjects];
    [self.sectionTitles removeAllObjects];
    
    NSMutableArray *contactArray = [NSMutableArray arrayWithArray:aContactList];
    
    //建立索引的核心, 返回27，是a－z和＃
    UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
    [self.sectionTitles addObjectsFromArray:[indexCollation sectionTitles]];
    
    NSInteger highSection = [self.sectionTitles count];
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:highSection];
    for (int i = 0; i < highSection; i++) {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sortedArray addObject:sectionArray];
    }
    
    //按首字母分组
    for (ContactModel *contact in contactArray) {
        NSString * name;
        if (_type == 3) {
            name = contact.remark;
        }else if(_type == 4){
            name = contact.remark;
        }else{
            name = contact.nickname;
        }
        NSString *firstLetter = [EMChineseToPinyin pinyinFromChineseString:name];
        NSInteger section;
        if (firstLetter.length > 0) {
            section = [indexCollation sectionForObject:[firstLetter substringToIndex:1] collationStringSelector:@selector(uppercaseString)];
        } else {
            section = [sortedArray count] - 1;
        }
        
        NSMutableArray *array = [sortedArray objectAtIndex:section];
        [array addObject:contact];
    }
    
    //每个section内的数组排序
    for (int i = 0; i < [sortedArray count]; i++) {
        NSArray *array = [[sortedArray objectAtIndex:i] sortedArrayUsingComparator:^NSComparisonResult(ContactModel *contact1, ContactModel *contact2) {
            NSString *firstLetter1 = [EMChineseToPinyin pinyinFromChineseString:contact1.username];
            firstLetter1 = [[firstLetter1 substringToIndex:1] uppercaseString];
            
            NSString *firstLetter2 = [EMChineseToPinyin pinyinFromChineseString:contact2.username];
            firstLetter2 = [[firstLetter2 substringToIndex:1] uppercaseString];
            
            return [firstLetter1 caseInsensitiveCompare:firstLetter2];
        }];
        
        [sortedArray replaceObjectAtIndex:i withObject:[NSMutableArray arrayWithArray:array]];
    }
    
    //去掉空的section
    for (NSInteger i = [sortedArray count] - 1; i >= 0; i--) {
        NSArray *array = [sortedArray objectAtIndex:i];
        if ([array count] == 0) {
            [sortedArray removeObjectAtIndex:i];
            [self.sectionTitles removeObjectAtIndex:i];
        }
    }
    //    [sortedArray addObject:@""];
    [self hideHud];
    [self.dataSources addObjectsFromArray:sortedArray];
    [self.tableView reloadData];
    [self.userlistView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_isSearchRes) {
        return 1;
    }
    return self.dataSources.count;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_isSearchRes) {
        return self.searchArr.count;
    }
    return [self.dataSources[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FirendsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"startGroupCell"];
    cell.groupMerrDelete = _type;
    if (_isSearchRes) {
        cell.model = self.searchArr[indexPath.row];
    }else{
        cell.model = self.dataSources[indexPath.section][indexPath.row];
        cell.index_section=indexPath.section;
        cell.index_row=indexPath.row;
        cell.delegate=self;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_type == 4 && _isMaster) {
        ContactModel * model = self.dataSources[indexPath.section][indexPath.row];
        FriendsInfoViewController * infoVC = [[FriendsInfoViewController alloc]init];
        infoVC.Fuuid = model.fuuid;
        infoVC.type = @"search";
        [self.navigationController pushViewController:infoVC animated:YES];
    }else if (_type==5)
    {
        ContactModel * model = self.dataSources[indexPath.section][indexPath.row];
        if (self.selectedSuccessBlcok) {
            self.selectedSuccessBlcok(@"1",model.remark, model.fuuid);
        }
        [self.navigationController  popViewControllerAnimated:YES];
//        NSLog(@"选择用户=fuuid=%@,id=%@,username=%@",model.fuuid,model.user_id,model.remark);
    }
}

-(void)FirendsTableViewCellWithClickSelecdCell:(FirendsTableViewCell *)cell
{
    ContactModel * model = self.dataSources[cell.index_section][cell.index_row];
    if (cell.invitationBtn.selected) {
        model.seleoctedState=YES;
        [self.collectionDataArray addObject:model];
    }else
    {
        model.seleoctedState=NO;
        [self.collectionDataArray removeObject:model];
    }
    
    [self.userlistView reloadData];
    [self scrollBottom];
    /*群发添加群聊消息*/
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.sectionTitles;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 36;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = kColor_LightGray;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, tableView.frame.size.width - 20, 20)];
    label.center = CGPointMake(tableView.frame.size.width/2, 18);
    label.textColor = KHEXCOLOR(@"#AFAFAF");
    label.backgroundColor = kColor_LightGray;
    label.font = [UIFont systemFontOfSize:15];
    
    NSString *title;
    if (_isSearchRes && self.searchArr.count != 0) {
        title = [NSString stringWithFormat:@"搜查结果共计%ld条",self.searchArr.count];
    }else{
        if (_type == 4) {
            if (section == 0) {
                title = @"群主";
            }else{
                title = @"群成员";
            }
        }else{
            title = self.sectionTitles[section];
        }
    }
    label.text = [NSString stringWithFormat:@"  %@", title];
    [view addSubview:label];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(MJTableViewNullDataView*)nullDataView {
    if (!_nullDataView) {
        _nullDataView=[[MJTableViewNullDataView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, self.tableView.frame.size.height-60)];
        _nullDataView.hidden=YES;
        _nullDataView.backgroundColor=[UIColor whiteColor];
    }
    [_nullDataView setCustomViewFrame:@"空状态" message:@"搜索无结果"];
    return _nullDataView;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
